<?php
namespace app\scodetrace\controller;

class TraceLogs extends \app\common\controller\Base {
	protected $modelname='TraceLog';

	protected function _index(){
		return null;
	}

	public function index() {
		$logModel=model($this->modelname);
		$data = [];
		$param=$this->param;
		if (isset($param['id'])) {
			$m = model($this->modelname);
			if (count($ids=$m->getLogIds($param['id']))==0) {
				return json_pack("查找log失败",400);
			}
			$data = $m->page($this->param('page',1),$this->param('limit',10))->select($ids);
		} else if (isset($param['scode'])) {
			$scodes = db('xl_scode')->where('scode',"like","%".$param['scode']."%")->field(["scode","log_id"])->select();

			$group=[];
			foreach ($scodes as &$scode) {
				$group[$scode['log_id']][]=$scode['scode'];
			}
			foreach ($group as $k=>&$v) {
				if ($k) {
					$data[] = array_merge($logModel->get($k)->toArray(),['query'=>implode(',', $v)]);
				}
			}
		} else if (isset($param['batch'])) {
			$batches = db('xl_batch')->where('name',"like","%".$param['batch']."%")->field(["name","log_id"])->select();
			$group=[];
			foreach ($batches as &$batch) {
				$group[$batch['log_id']][]=$batch['name'];
			}
			foreach ($group as $k=>&$v) {
				if ($k && ($tmp=$logModel->get($k))) {
					$data[] = array_merge($tmp->toArray(), ['query'=>implode(',', $v)]);
				}
			}
		} else if (isset($param['batch_no'])) {
			$batches = db('xl_batch')->where('serial_number',"like","%".$param['batch_no']."%")->field(["name","log_id"])->select();
			$group=[];
			foreach ($batches as &$batch) {
				$group[$batch['log_id']][]=$batch['name'];
			}
			foreach ($group as $k=>&$v) {
				if ($k && ($tmp=$logModel->get($k))) {
					$data[] = array_merge($tmp->toArray(), ['query'=>implode(',', $v)]);
				}
			}
		}
		return json_pack($data);
	}

	public function count() {
		$param=$this->param;
		if (isset($param['id'])) {
			$m = model($this->modelname);
			$ids=$m->getLogIds($param['id']);
			return json_pack(count($ids));
		} else {
			return json_pack(0);
		}
	}
}

?>